package net.slashie.libjcsi.wswing;

import java.awt.event.*;
import java.lang.reflect.Field;

import javax.swing.text.StyledEditorKit.ForegroundAction;

import net.slashie.libjcsi.CharKey;

/**
 * Gets keyboard input.
 * 
 * @author Santiago Zapata
 * @author Eben Howard
 */
public class StrokeInformer implements KeyListener, java.io.Serializable {

	private int bufferCode;
	private transient Thread keyListener;

	public StrokeInformer() {
		bufferCode = -1;
	}

	/**
	 * 
	 * @param toWho
	 *            where to add keyListener
	 */
	public void informKey(Thread toWho) {
		keyListener = toWho;
	}

	/**
	 * 
	 * @return code shows what was input
	 */
	public int getInkeyBuffer() {
		return bufferCode;
	}

	/**
	 * Captures input
	 * 
	 * @param e
	 */
	@Override
	public void keyPressed(KeyEvent e) {
	}

	/**
	 * Takes raw input and turns it into CharKey encoding.
	 * 
	 * @param x
	 *            pressing of a key
	 * @return CharKey encoded value
	 */
	private int charCode(KeyEvent x) {
		char keyChar = x.getKeyChar();
		
		try {
 			Field declaredField = CharKey.class.getDeclaredField(keyChar + "");
			Integer charKeyCode = (Integer) declaredField.get(null);
			return charKeyCode.intValue();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// Silently Ignore
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		
		try {
 			Field declaredField = CharKey.class.getDeclaredField("T" + keyChar);
			Integer charKeyCode = (Integer) declaredField.get(null);
			return charKeyCode.intValue();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// Silently Ignore
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

		String keyString = "" + keyChar;
		if (CharKey.charsToCharKey.containsKey(keyString)) {
			return CharKey.charsToCharKey.get(keyString);
		}
		return CharKey.NONE;
	}

	/**
	 * Currently does nothing.
	 * 
	 * @param e
	 */
	@Override
	public void keyReleased(KeyEvent e) {
	}

	/**
	 * Currently does nothing.
	 * 
	 * @param e
	 */
	@Override
	public void keyTyped(KeyEvent e) {
		System.out.println(e.getKeyChar());
		bufferCode = charCode(e);
		keyListener.interrupt();
	}
}